package spt.services;

import java.util.List;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import spt.exceptions.SlideException;
import spt.exceptions.ValidationException;
import spt.slides.Slide;
import spt.slides.SlideManager;
import spt.slides.SlideXMLReader;
import spt.slides.SlideXMLWriter;
import spt.utils.ExceptionXMLWriter;
import spt.utils.ValueXMLWriter;

@Path("/backend/slide")
public class BackendResources {
	private final Logger log = Logger.getLogger(BackendResources.class
			.getName());

	private SlideManager slideManager;

	public BackendResources() {
		slideManager = new SlideManager();
	}

	@GET
	public String get(@QueryParam("id") int id) {
		Slide slide = null;
		try {
			slide = slideManager.getSlide(id);
			return SlideXMLWriter.write(slide);
		} catch (SlideException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		}
	}
	
	@GET
	@Path("/list")
	public String getAll(){
		List<Integer> slidesIds;
		try {
			slidesIds = slideManager.getSlidesIds();
			return SlideXMLWriter.writeIdsList(slidesIds);
		} catch (SlideException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		}
	}

	@PUT
	@Consumes("text/plain")
	public String add(String xml) {
		Slide slide = SlideXMLReader.read(xml);
		log.info(slide.toString());

		try {
			int id = slideManager.addSlide(slide);
			return ValueXMLWriter.write("id", Integer.toString(id));
		} catch (SlideException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		} catch (ValidationException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		}
	}

	@POST
	@Consumes("text/plain")
	public String update(String xml, @QueryParam("id") int id) {
		Slide slide = SlideXMLReader.read(xml);
		slide.setId(id);

		try {
			slideManager.updateSlide(slide);
			return "";
		} catch (SlideException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		} catch (ValidationException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		}
	}

	@DELETE
	public String delete(@QueryParam("id") int id) {
		try {
			slideManager.deleteSlide(id);
			return "";
		} catch (SlideException e) {
			log.warning(e.getMessage());
			return ExceptionXMLWriter.write(e);
		}
	}
}
